<template>
  <div id="container">
    <h2>周计划清单</h2>
    <div class="task">
      <div class="addtaskDiv">
        <input
          class="addTaskInput"
          type="text"
          v-model="newTask"
          placeholder="添加新任务名称"
          @keydown.enter="addTask"
        />
        <i class="iconfont icon-add" @click="addTask"></i>
      </div>
      <ul>
        <li v-for="(item, index) in taskList" :key="index">
          <todo-item :item="item" @toggle="handleToggle" @delete="handleDelete"></todo-item>
        </li>
      </ul>
    </div>
    <footer>共{{ totalCount }}条/已完成{{ doneCount }}条</footer>
  </div>
</template>

<script>
import TodoItem from '@/components/TodoItem'
export default {
  name: 'APP',
  components: {
    TodoItem
  },
  data() {
    return {
      // 输入框的值
      newTask: '',
      // 任务列表
      taskList: []
    }
  },
  methods: {
    // 添加任务
    addTask() {
      if (!this.newTask) return alert('任务名称不能为空')
      this.taskList.push({
        id: Date.now(),
        name: this.newTask,
        isDone: false
      })
      this.newTask = ''
    },
    // 完成任务
    handleToggle(id, isCheck) {
      const index = this.taskList.findIndex((item) => item.id === id)
      this.taskList[index].isDone = isCheck
    },
    // 删除任务
    handleDelete(id) {
      const index = this.taskList.findIndex((item) => item.id === id)
      this.taskList.splice(index, 1)
    }
  },
  computed: {
    // 计算已完成的任务条数
    doneCount() {
      return this.taskList.filter((item) => item.isDone).length
    },
    // 计算任务总数
    totalCount() {
      return this.taskList.length
    }
  }
}
</script>

<style lang="scss" scoped>
#container {
  width: 500px;
  height: 500px;
  border: 1px solid #000;
  border-radius: 10px;
  margin: 0 auto;
  margin-top: 100px;
  padding: 10px;
  display: flex;
  flex-direction: column;
  h2 {
    text-align: center;
  }
  .task {
    width: 100%;
    padding: 10px;
    flex: 1;
    display: flex;
    flex-direction: column;
    .addtaskDiv {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
    .addTaskInput {
      flex: 1;
      height: 30px;
      margin: 20px 0;
      padding-left: 10px;
      border: 1px solid #ccc;
      border-radius: 5px;
      font-size: 14px;
      &:focus {
        border-color: #000;
      }
    }
    ul {
      flex: 1;
      overflow-y: auto; // Enable vertical scrolling
      max-height: 300px; // Set a maximum height for the list container
      padding-right: 10px; // Add some padding to accommodate scrollbar
      li {
        list-style: none;
      }
    }
  }
  footer {
    padding: 10px;
  }
  .icon-add {
    font-size: 30px;
    color: green;
    margin-left: 5px;
  }
}
</style>
